/**
 * LinkedLST
 * May 11, 2011
 * LoginView.java - Login activity
 */

package edu.washington.cs.labspecimentransport;
import java.io.UnsupportedEncodingException;

import org.apache.http.conn.ConnectTimeoutException;

import edu.washington.cs.labspecimentransport.data.DataQuery;
import edu.washington.cs.labspecimentransport.ops.CommonHandlers;
import edu.washington.cs.labspecimentransport.ops.Keys;
import edu.washington.cs.labspecimentransport.ops.Settings;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * LoginView is the starting screen for the Lab Specimen Transport application.
 * Users are required to enter their username and password to login before accessing
 * the rest of the application.
 */
public class LoginView extends Activity {
	private boolean loginSuccessful;	// flag for successful login
	private EditText userField;			// the username text field
	private EditText passwordField;		// the password text field
	
	private int courierId;				// id of logged in courier

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		setupButtons();	// sets onClick handler for all buttons
		userField = (EditText) findViewById(R.id.username_field);
		passwordField = (EditText) findViewById(R.id.password_field);
		loginSuccessful = false;
		
		// automatically populate username and password fields if debug/test mode is on
		if (Settings.debugMode || Settings.testMode) {
			userField.setText(Settings.debugUser);
			passwordField.setText(Settings.debugPass);
		}
	}
	
    /**
     * Push the activity to the back when back button is pressed.
     */
    public void onBackPressed() {
    	moveTaskToBack(true);
    }
	
    /**
     * Define the options menu.
     */
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0, Keys.MENUID_HELP, 0, R.string.option_help);
    	return true;
    }

    /**
     * Define functionality for each item in options menu.
     */
    public boolean onOptionsItemSelected(MenuItem item) {   
        switch(item.getItemId()) {
        case Keys.MENUID_HELP:
        	CommonHandlers.startHelp(this);
        	break;
        default:
        	super.onOptionsItemSelected(item);
        	break;
        }
        return true;
    }

	/**
	 * Sets the onClick handlers for all buttons
	 */
	public void setupButtons() {
		// onClick handler for "Login" button
		Button login = (Button) findViewById(R.id.login_submit);
		login.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				new Login().execute();
			}
		});
	}

	/**
	 * Handler for successful login
	 */
	public void loginSuccessful() {    	
		Intent i = new Intent(LoginView.this, HomeView.class);
		Bundle b = new Bundle();
		b.putInt(Keys.KEY_COURIERID, courierId);
		b.putBoolean(Keys.KEY_CHECKLIST_BEFORE, false);
		b.putBoolean(Keys.KEY_CHECKLIST_AFTER, false);
		i.putExtras(b);

		startActivity(i);
		finish();
	}

	/**
	 * Service to authenticate user login with the backend.
	 */
	private class Login extends AsyncTask<Void, Void, Void> {
		private ProgressDialog dialog;
		private boolean empty;
		private boolean timeout;

		// before execution
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			empty = false;
			timeout = false;
			loginSuccessful = false;
			dialog = ProgressDialog.show(LoginView.this, "", 
					getString(R.string.login_load), true, true,
					new DialogInterface.OnCancelListener(){
				public void onCancel(DialogInterface dialog) {
					Login.this.cancel(true);
					onBackPressed();
				}
			});
		}

		// execution
		@Override
		protected Void doInBackground(Void... unused) {

			try {
				String username = userField.getText().toString();
				username = java.net.URLEncoder.encode(username, "UTF-8");
				String password = passwordField.getText().toString();
				password = java.net.URLEncoder.encode(password, "UTF-8");

				if (username.equals("") || password.equals("")) {
					empty = true;
				} else {
					loginSuccessful = DataQuery.getInstance().authenticate(
							username, 
							password);

					if (loginSuccessful) {
						courierId = DataQuery.getInstance().getCurrentCourier().getId();
					}
				}
			} catch (ConnectTimeoutException e) {
				timeout = true;
			} catch (UnsupportedEncodingException e) {
			}
			return null;
		}

		// after execution
		@Override
		protected void onPostExecute(Void unused) {
			dialog.dismiss();

			if (loginSuccessful) {
				loginSuccessful();
			} else if (empty) {
				// no username or password was entered
				Toast toast = Toast.makeText(
						LoginView.this, R.string.login_error_emptyInfo,
						Toast.LENGTH_LONG);
				toast.show();
			} else if (timeout) {
				// unable to access server
				Toast toast = Toast.makeText(
						LoginView.this, R.string.error_timeout,
						Toast.LENGTH_LONG);
				toast.show();
			} else {
				// invalid username and/or password
				Toast toast = Toast.makeText(
						LoginView.this, R.string.login_error,
						Toast.LENGTH_LONG);
				toast.show();
			}
		}
	}       
}